﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace Bradaz.OpenSource.IO
{
    #region Streams
    /// <summary>
    /// Static Utility to deal with common Stream task.
    /// </summary>
    public static class Streams
    {
        /// <summary>
        /// Static method to handle returning the offset of a stream to zero (Beginning)
        /// </summary>
        /// <param name="stream">ref Stream</param>
        public static void RewindStream(ref Stream stream)
        {
            if (stream.CanSeek)
            {
                //--If the stream can seek, return the offset back to the beginning using the correct Seek Method.
                stream.Seek(0, SeekOrigin.Begin);

            }
            else
            {
                //--Store the InputStream in memory which will return it to the beginning
                //--NB: THis is done within a "using" statement so the relevant Dispose 
                //--methods will be handled.
                using (MemoryStream memoryStream = new MemoryStream())
                {
                    //--Create a memory buffer.
                    byte[] buffer = new byte[stream.Length];
                    int bytesRead;

                    //--Read the input stream into memory.
                    while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) > 0)
                    {

                        memoryStream.Write(buffer, 0, bytesRead);
                    }

                    //--Reset the position to the beginning of the stream.
                    memoryStream.Position = 0;

                    //--Re-write the memoryStream back into the input stream.
                    byte[] memoryStreamBuffer = new byte[memoryStream.Length];
                    while ((bytesRead = memoryStream.Read(memoryStreamBuffer, 0, (int)memoryStream.Length)) > 0)
                    {
                        stream.Write(memoryStreamBuffer, 0, bytesRead);

                    }

                }
            }

        }

    }
    #endregion
}

